
package hk.ces.oxfam.patch.xml.factory;

import hk.ces.oxfam.patch.xml.SimpleXML;
import org.dom4j.Element;

/**
 *
 * @author ReutyCheng
 */
public class SimpleXMLFactory
{
  private String nodeHeaders = "Headers";
  private String nodeHeader = "Header";
  private String nodeBodyItems = "BodyItems";
  private String nodeBodyItem = "BodyItem";
  private String nodeItem = "Item";

  private SimpleXML simpleXML = null;

  public void resetNodeName(String[] nodeNames)
  {
    if (nodeNames == null)
    {
      // Do nothing
      return;
    }
    else
    {
      if (nodeNames.length != 5)
      {
        throw new IllegalArgumentException("Reset Node Names should must be length 5. Now is length : " + nodeNames.length);
      }
      
      nodeHeaders = nodeNames[0] != null ? nodeNames[0] : nodeHeaders;
      nodeHeader = nodeNames[1] != null ? nodeNames[1] : nodeHeader;
      nodeBodyItems = nodeNames[2] != null ? nodeNames[2] : nodeBodyItems;
      nodeBodyItem = nodeNames[3] != null ? nodeNames[3] : nodeBodyItem;
      nodeItem = nodeNames[4] != null ? nodeNames[4] : nodeItem;
    }
  }

  public void setSimpleXML(SimpleXML simpleXML)
  {
    this.simpleXML = simpleXML;
  }

  public Element createHeaders(Element parentElement)
  {
    if (simpleXML == null)
    {
      throw new NullPointerException("Simple XML is null. Please Set SimpleXML first");
    }
    
    Element columnsElement = parentElement.addElement(nodeHeaders);
    for (String columnName : simpleXML.getHeader())
    {
      Element columnElement = columnsElement.addElement(nodeHeader);
      columnElement.setText(columnName);
    }
    return columnsElement;
  }

  public Element createBodyItems(Element parentElement)
  {
    if (simpleXML == null)
    {
      throw new NullPointerException("Simple XML is null. Please Set SimpleXML first");
    }

    Element rowsElement = parentElement.addElement(nodeBodyItems);
    for (Object[] objects : simpleXML.getBodyItem())
    {
      Element rowElement = rowsElement.addElement(nodeBodyItem);
      for (Object object : objects)
      {
        Element objectElement = rowElement.addElement(nodeItem);
        objectElement.setText(object != null ? object.toString() : "");
      }
    }
    return rowsElement;
  }
}
